package com.tmobile.databaseprepare;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import android.content.Context;
import android.text.Html;
import android.util.Log;

import com.tmobile.databaseprepare.database.BookDatabase;

public class Crawler {
	public static final String TAG = Crawler.class.getSimpleName();
	// public static final int START_CHAPTER_INDEX = 262538;//mat ma tay tang
	// public static final int START_CHAPTER_INDEX = 239459; //nu trinh sat
	// public static final int CHAPTER_TOTAL = 17;//nu trinh sat
	// public static final int CHAPTER_TOTAL = 86;//mat ma tay tang

	// public static final int START_CHAPTER_INDEX = 266890; // tamthaitu
	// public static final int CHAPTER_TOTAL = 197;// tamthaitu
	// public static final int START_CHAPTER_INDEX = 230161; //
	// hopdonghonnhan100ngay
	// public static final int CHAPTER_TOTAL = 405;// hopdonghonnhan100ngay
	// public static final int START_CHAPTER_INDEX = 136427; //
	// covotonggiamdocxinhdepcuatoi
	// public static final int CHAPTER_TOTAL = 1663;//
	// covotonggiamdocxinhdepcuatoi
	// public static final String BASE_URL =
	// "http://sstruyen.com/doc-truyen/index.php?ajax=ct&id=";
	public static final int START_CHAPTER_INDEX = 246831; // tayuyen
	public static final int CHAPTER_TOTAL = 41;// tayuyen
	public static final String BASE_URL = "http://sstruyen.com/doc-truyen/index.php?ajax=ct&id=";

	BookDatabase bookDatabase;

	public Crawler(Context ctx) {
		bookDatabase = BookDatabase.getInstance(ctx);
	}

	public Document crawlUrl(String url, int chapterIndex) {
		// String cssQuery1 = "span#chapt-content";
		// String cssQuery1 = "div.detail-content";
		String cssQuery1 = "body";
//		String test  = "http://www.doctruyen360.com/co-vo-tong-giam-doc-xinh-dep-cua-toi-chuong-1661/";
		try {
			Document doc = Jsoup.connect(url).data("query", "Java")
					.userAgent("CoRom/33.0.1750.154").cookie("auth", "token")
					.timeout(10000).get();
			// Elements contents = doc.select(cssQuery1);
			// Log.i(TAG, "text content = " + Html.fromHtml(doc.html()));
			insertToDB(doc);
			Log.d(TAG, "insert chapter" + chapterIndex);
			return doc;
		} catch (Exception e) {
			Log.i(TAG, "" + e.toString());
		}
		return null;
	}

	public void insertToDB(Document doc) {
		com.tmobile.databaseprepare.database.Book bookRecord = new com.tmobile.databaseprepare.database.Book();
		bookRecord.setBookNumber(1);
		bookRecord.setChapterTitle("");
//		Elements contents = doc.select("div#content");
//		Log.d(TAG, "content = "+ Html.fromHtml(contents.html()));
		Log.i(TAG, ""+doc.html());
		bookRecord.setChapterContent(doc.html());
		bookDatabase.createRecord(bookRecord);
	}
}
